﻿using Chaunce.Web.Core.Helpers;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using Chaunce.Web.Core;
using Chaunce.FrameWork.NetCore.Utility.Exceptions;
using Chaunce.FrameWork.NetCore.SysCore.Consts;
using Chaunce.FrameWork.NetCore.Chaunce.Utility.Helpers;

namespace Chaunce.Web.Core.Filters
{
    /// <summary>
    /// 权限控制过滤器
    /// </summary>
    public class PermissionActionFilter : IAsyncActionFilter
    {
        public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            var descriptor = (Microsoft.AspNetCore.Mvc.Controllers.ControllerActionDescriptor)context.ActionDescriptor;
            var controllName = descriptor.ControllerName;
            var actionName = descriptor.ActionName;
            var identity = context.HttpContext.User.Identity;
            var userId = identity.GetUserId<long>();
            var roleName = identity.GetRoleName();
            var ret = PermissionHelper.HasPermission(userId, controllName, actionName, roleName: roleName);
            if (!ret)
            {
                //context.HttpContext.Response.StatusCode = 200;
                //context.HttpContext.Response.ContentType = "application/json";
                string errorMsg = "用户无权访问!";
                //context.Result = errorMsg.ToErrorActionResult(AppErrorCode.PermissionDenied.ToInt());
                throw new ChaunceException(errorMsg, AppErrorCode.PermissionDenied.ToInt());
                //return;
            }
            await next();
        }
    }
}
